import {
  getProductWarehouseReceiptList,
  addProductReceiveOrderOrder,
  updateProductReceiveOrderOrder,
  updateProductInspectionOrderStatus
} from "@/api/productionManagement/finishedProductWarehouseReceipt.js";

import { formatDate } from "@/uitils/publicMethod.js"
export const myMethod = {
  formatDate,
  // 排序
  sortChange(val) {},
  // 选中表格数据
  tableSelectionChange(val) {
    this.tableSelection = val;
    console.log(val);
  },
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 调整状态显示文案和样式
  getAuditStatus(val) {
    // 1 审核通过   0 审核不通过    null 未审核
    // 目前只有三种状态 对象最后一个元素代表null的状态，后续有新增请在对应的倒数第二个位置添加
    const typeObj = {
      0: "danger",
      1: "primary",
      2: "warning",
    };
    const infoObj = {
      0: "审核失败",
      1: "审核成功",
      2: "未审核",
    };
    return {
      type:
        val !== null
          ? typeObj[val]
          : typeObj[Object.keys(typeObj)[Object.keys(typeObj).length - 1]],
      info:
        val !== null
          ? infoObj[val]
          : infoObj[Object.keys(infoObj)[Object.keys(infoObj).length - 1]],
    };
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 清空弹框的数据
  closeChange() {
    this.$refs.addFormRef.resetForm()
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { WorkOrderCode } = this.form;
      const params = {
        ProductReceiveCode: WorkOrderCode || "", // 产成品入库单编码
        rows: this.pageSize,
        page: this.currentPage,
      };
      const res = await getProductWarehouseReceiptList(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  // 点击审核操作
  async auditChange(type) {
    if (this.tableSelection.length == 0) {
      return this.$message.error("请选择要审批的行!");
    }
    if (this.tableSelection.length != 1) {
      return this.$message.error("只能选择一行数据进行审批!");
    }
    // null 未审核   0 审核失败   1 审核成功
    if (this.tableSelection[0].status === 1) {
      const approver = `已经审批的产成品入库单${this.tableSelection[0].productInspectionCode}不允许重复审批!`;
      return this.$message.error(approver);
    }
    this.selectAuditType = type;
    try {
      const params = {
        productReceiveId: this.tableSelection[0].productReceiveId, // 产成品入库单Id
        status: this.selectAuditType, // 状态 0是放审 1是审核 2是删除
      };
      const result = await updateProductInspectionOrderStatus(params);
      console.log(result);
      if (result.ok) {
        this.$message.success("审核成功");
        // 清空查询条件
        this.tableSelection = []
        this.resetPage();
        // 刷新列表数据
        this.getTableData();
      } else {
        this.$message.error((result.err && result.err.msg) || "审核失败");
      }
    } catch (err) {
      console.error("数据异常", err);
    }
  },
  addChange() {
    this.addTitle = "添加产成品入库单";
    this.isShowConfirmBtn = true
    this.$refs.addDialogComRef.dialogVisible = true;
    // 获取下拉框列表数据
    this.processData();
    this.$nextTick(()=> {
      // 检验时间默认当前
      this.$refs.addFormRef.forms.productReceiveDate = this.formatDate(new Date())
    })
  },
  // 获取仓库列表数据
  async getWarehouseList() {
    const params = {
        page: 1,
        rows: 10000,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify([])
    }
    const url = `/api/Warehouse/getPageData`;
    return this.http
      .post(url, params, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取存货列表数据
  async getInventoryList() {
    const params = {
        page: 1,
        rows: 10000,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify([])  // 转为 JSON 字符串
    }
    const url = `/api/Inventory/getPageData`;
    return this.http
      .post(url, params, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  async processData() {
    this.$refs.addDialogComRef.loading = true;
    try {
      const [data1, data2] = await Promise.all([
        this.getWarehouseList(),
        this.getInventoryList(),
      ]);
      this.$refs.addFormRef.wareHouseOptions = data1 ? JSON.parse(JSON.stringify(data1)) : [];
      this.$refs.addFormRef.inventoryNameOption = data2 ? JSON.parse(JSON.stringify(data2)) : [];
      this.$refs.addDialogComRef.loading = false;
    } catch (error) {
      this.$refs.addDialogComRef.loading = false;
      console.error("获取数据失败:", error);
    }
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.addFormRef.confirmChange();
  },
  async okChange() {
    console.log('通过校验');
    try {
        this.$refs.addDialogComRef.loading = true;
        const {
            productReceiveCode,
            productReceiveDate,
            warehouseId,
            productInspectionId,
            remark,
        } = this.$refs.addFormRef.forms;
        const params = {
          "productReceiveCode": productReceiveCode || '', // 产成品入库单编码
          "productReceiveDate": productReceiveDate, // 检验时间
          "warehouseId": warehouseId, // 仓库id
          "productInspectionId": productInspectionId, // 产品检验单id
          "remark": remark, // 备注
          "addProductReceiveOrderDetails": this.$refs.addFormRef.addProductReceiveOrderDetails.map((item) => {
                let obj = {
                    warehouseId: item.warehouseId || null, // 仓库id
                    inventoryId: item.inventoryId, // 存货id
                    quantity: Number(item.quantity)     // 数量
                }
                // 如果仓库不存在 则删除字段
                if(!item.warehouseId) {
                    delete obj.warehouseId
                }
                return obj;
            }), // 仓库 存货 数量集合
        }
        const isAdd = !this.$refs.addFormRef.forms.productReceiveId;
        const text = isAdd ? "添加" : "修改";
        if (!isAdd) {
        params.productReceiveId =
            this.$refs.addFormRef.forms.productReceiveId;
        }
        const apiName = isAdd ? addProductReceiveOrderOrder : updateProductReceiveOrderOrder;
        const result = await apiName(params);
        if (result.ok) {
          this.$message.success(text + "成功");
          this.$refs.addDialogComRef.dialogVisible = false;
          if (isAdd) this.currentPage = 1;
          this.closeChange();
          this.getTableData();
        } else {
          this.$message.error(
              (result.err && result.err.msg) || text + "失败"
          );
        }
        this.$refs.addDialogComRef.loading = false;
    } catch (err) {
        this.$refs.addDialogComRef.loading = false;
        console.error("数据异常:", err);
    }
  },
  detailChange(val) {
    this.updateChange(val);
  },
  updateChange(val) { // type 1修改 2详情
    this.addTitle = "产成品入库单明细";
    this.isShowConfirmBtn = false
    this.$refs.addDialogComRef.dialogVisible = true;
    this.$nextTick(() => {
      this.$refs.addFormRef.forms = JSON.parse(JSON.stringify(val))	;
      this.$refs.addFormRef.addProductReceiveOrderDetails =
      this.$refs.addFormRef.forms.addProductReceiveOrderDetails.map(
        (item, index) => {
          return {
            key: index,
            warehouseId: item.warehouseId || null,
            inventoryId: item.inventoryId,
            quantity: item.quantity
          };
        }
      );
    });
    // 获取下拉框列表数据
    this.processData();
  },
  async deleteChange(val) {
    // 审核成功不允许删除
    if(val.status === 1) {
      const approver = `已经审批通过的产成品入库单${val.productInspectionCode}不允许删除!`;
      return this.$message.error(approver);
    }
    // 切换页码
    const oldCurrentPage = this.currentPage;
    const temp = Math.ceil(Math.max(this.totalPage - 1, 1) / this.pageSize);
    if (this.currentPage > temp) {
      this.currentPage = temp;
    }
    this.$refs.dataTableRef.tableLoading = true;
    try {
       const params = {
        productReceiveId: val.productReceiveId, // 产成品入库单Id
        status: 2, // 状态 0是放审 1是审核 2是删除
      };
      const res = await updateProductInspectionOrderStatus(params);
      if (res.ok) {
        this.$message.success("删除成功");
        this.getTableData();
      } else {
        this.currentPage = oldCurrentPage;
        this.$message.error((res.err&&res.err.msg) || "删除失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.currentPage = oldCurrentPage;
      this.$message.error((err.err&&err.err.msg) || "删除失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
};
